package com.imut.hcdp.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.imut.hcdp.config.AliPayConfig;
import com.imut.hcdp.domain.AliPay;
import com.imut.hcdp.domain.HcdpOrder;
import com.imut.hcdp.mapper.HcdpOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付宝沙箱：https://open.alipay.com/develop/sandbox/account
 * 测试账号：
 *      peghxk8819@sandbox.com
 *      111111
 */

@Controller
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private HcdpOrderMapper hcdpOrderMapper;


    /**
     * 沙箱支付
     * @param aliPay subject:购票 traceNo:流水号 totalAmount：总金额
     * @param httpResponse
     * @throws IOException
     */
    @GetMapping("/pay")
    @ResponseBody
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                "JSON",
                "utf-8",
                aliPayConfig.getAlipayPublicKey(),
                "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + "utf-8");
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }



    @PostMapping("/notify")
    @ResponseBody
    public String returnUrlMethod(HttpServletRequest request, HttpSession session) throws AlipayApiException, UnsupportedEncodingException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params,  aliPayConfig.getAlipayPublicKey(), "utf-8", "RSA2"); // 调用SDK验证签名
        System.out.println("签名是否成功：" + signVerified);
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 支付宝交易流水号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 付款金额
        float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));
        System.out.println("商户订单号="+out_trade_no);
        System.out.println("支付宝交易号="+trade_no);
        System.out.println("付款金额="+money);
        HcdpOrder hcdpOrder = new HcdpOrder();
        hcdpOrder.setOutTradeNo(out_trade_no);
        hcdpOrder.setStatus(2L);//已支付
        int i = hcdpOrderMapper.updateHcdpByLs(hcdpOrder);
        System.out.println("订单是否支付成功：" + (i==1?"是":"否"));
        return "success";

    }


}
